package MWClient;

import java.util.HashMap;
import java.util.Map;

import jssc.SerialPort;
import org.json.simple.JSONValue;

/**
 * <pre>
 * @Package : MWClient
 * @File    : SerialSender.java
 * <pre>
 *
 * @Author  : 차재우
 * @Date    : 2013. 7. 22.
 * @Version :
 */
class SerialSender implements Runnable {
	private SerialPort sp = null;
	
	private final int STX = 2;
	private final int ETX = 2;
	private final int SIZE = 4;
	

	/**
	 * <pre>
	 * @Comment : 생성자
	 * <pre>
	 *
	 * @param sp
	 */
	public SerialSender(SerialPort sp) {
		this.sp = sp;
	}
	
	/**
	 * <pre>
	 * @Comment : 테스트 데이터 생성
	 * <pre>
	 *
	 * @Method  : SerialTestData
	 * @return
	 */
	private byte[] SerialTestData() {
		Map<String, String> obj = new HashMap<String, String>();

		obj.put("TRNO", "RM01");
		obj.put("ITYPE", "O");
		obj.put("CSERNO", "S12345");
		obj.put("BTHYMD", "19811220");
		obj.put("SEXCD", "M");
		obj.put("DEPTCD", "01");
		obj.put("ISUNO", "1234");
		obj.put("ISUDT", "20130701");
		obj.put("IOTYPE", "I");

		String jsonStr = JSONValue.toJSONString(obj);

		return jsonStr.getBytes();
	}
	
	/**
	 * <pre>
	 * @Comment : 시리얼로 전송할 패킷으로 생성
	 * <pre>
	 *
	 * @Method  : MakeSerialPacket
	 * @return
	 */
	private byte[] MakeSerialPacket() {
		byte[] dataPart = SerialTestData();

		int dataSize = dataPart.length;
		int bufSize = STX + SIZE + dataSize + ETX;
		byte[] sendBuf = new byte[bufSize];

		int idx = 0;
		byte[] stx = { (byte) 0x01, (byte) 0x01 };
		byte[] etx = { (byte) 0x02, (byte) 0x02 };
		byte[] size = ByteUtil.toBytes(dataPart.length);
		
		System.arraycopy(stx, 0, sendBuf, idx, STX);			idx += STX;
		System.arraycopy(size, 0, sendBuf, idx, SIZE);			idx += SIZE;
		System.arraycopy(dataPart, 0, sendBuf, idx, dataSize);	idx += dataPart.length;
		System.arraycopy(etx, 0, sendBuf, idx, ETX);
		
		return sendBuf;
	}

	/**
	 * <pre>
	 * @Comment : 시리얼 통신 전송 스레드
	 * <pre>
	 *
	 * @Method  : run
	 */
	public void run() {
		while(true) {
			try {
				int term = 1 + (int)(Math.random() * 10);
				Thread.sleep(term * 1000);
				
				byte[] data = MakeSerialPacket();
				sp.writeBytes(data);
				
				System.out.println("\n***************************************************************************************************************************************");
				System.out.println("Serial sender term : " + term);
				System.out.println("Data size          : " + data.length);
			} catch (InterruptedException e) {
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
